import { Reporter } from './reporter';
import { BehaviorSubType, ReportData } from '../types';
import { sanitizeData } from '../utils/helper';

export class BehaviorMonitor {
  private reporter: Reporter;
  private pageEnterTime: number = Date.now(); // 页面进入时间

  constructor(reporter: Reporter) {
    this.reporter = reporter;
    this.init();
  }

  /**
   * 初始化行为监控
   */
  init() {
    // 监控页面浏览时长（离开页面时上报）
    window.addEventListener('beforeunload', () => this.reportPageView());

    // 自动监控点击行为（可选，需用户手动开启）
    // this.autoTrackClick();
  }

  /**
   * 上报页面浏览行为
   */
  private reportPageView() {
    const stayTime = Date.now() - this.pageEnterTime;
    this.reporter.push({
      type: 'behavior',
      subType: 'page_view' as BehaviorSubType,
      pageUrl: window.location.href,
      referrer: document.referrer,
      stayTime // 停留时长（ms）
    });
  }

  /**
   * 自动监控点击行为（可选择性开启）
   */
  autoTrackClick() {
    document.addEventListener('click', (event) => {
      const target = event.target as HTMLElement;
      // 过滤不需要监控的元素（如input、textarea）
      if (target.tagName.match(/^(INPUT|TEXTAREA|BUTTON)$/i)) {
        this.reporter.push({
          type: 'behavior',
          subType: 'click' as BehaviorSubType,
          tag: target.tagName.toLowerCase(),
          text: target.innerText?.slice(0, 50) || '', // 限制文本长度
          selector: this.getSelector(target), // 元素选择器
          timestamp: Date.now()
        });
      }
    }, true);
  }

  /**
   * 生成元素选择器（用于定位点击位置）
   */
  private getSelector(element: HTMLElement): string {
    if (element.id) return `#${element.id}`;
    if (element.tagName === 'BODY') return 'body';
    
    let selector = element.tagName.toLowerCase();
    if (element.className) {
      selector += `.${(element.className as string).replace(/\s+/g, '.')}`;
    }
    
    return `${this.getSelector(element.parentElement as HTMLElement)} > ${selector}`;
  }

  /**
   * 手动上报自定义行为
   */
  track(action: string, data: Record<string, any> = {}) {
    const reportData: ReportData = {
      type: 'behavior',
      subType: 'custom' as BehaviorSubType,
      action,
      ...sanitizeData(data) // 脱敏处理
    };
    this.reporter.push(reportData);
  }
}